<?php

namespace app\jigou\controller\qingdongams\department;

use addons\qingdongams\model\StaffRole;
use addons\qingdongams\model\StaffRule;
use app\jigou\controller\qingdongams\Base;
use addons\qingdongams\model\Staff;

/**
 * 角色管理
 * @icon fa fa-users
 */
class Role extends Base
{
    /**
     * @var \addons\qingdongams\model\StaffRole
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new StaffRole();
    }

    /**
     * 权限配置
     * @return string
     */
    public function rule($ids=null)
    {
        $map['id'] = $ids;
        if ($this->request->isAjax()) {
            $data   = $this->request->post('row/a');

            $result = $this->model->save(['rules'=>$data['rules'],'role_type'=>$data['role_type']], $map);

            if (!$result) {
                $this->error('修改失败');
            }
            $this->success('修改成功');
        }
        $row=$this->model->get($ids);
        if(empty($row)){
            $this->error('信息不存在');
        }
        $rule=[1=>'本人',2=>'本人及下属',3=>'本部门',4=>'仅下属部门',5=>'本部门及下属部门',6=>'全部'];

        $this->view->assign('row',$row);
        $this->view->assign('rule',$rule);
        return $this->view->fetch();
    }

    /**
     * 获取菜单
     * @param null $ids
     */
    public function roletree($ids=null){

        $data = $this->model::where(['id'=>intval($ids)])->find();
        if(empty($data)){
            $this->error('数据不存在');
        }
        $rules=explode(',',$data['rules']??'');
        $staffRules=StaffRule::where([])->order('weigh desc,id asc')->select();
        $roleList=[];
        foreach ($staffRules as $v) {
          if(empty($roleList)){
              $roleList[] = [
                  'id' => $v['pid'],
                  'parent' => '#',
                  'text' => '全部',
                  'type' => 'menu',
                  'state' => ['opened' => true],
              ];
          }
            $roleList[] = array(
                'id' => $v['id'],
                'parent' => $v['pid'] ?? '#',
                'text' => __($v['title']),
                'type' => 'menu',
                'state' => ['selected' => in_array($v['id'], $rules) ? true : false, 'opened' => true]
            );
        }
        $this->success('', null, $roleList);
    }
}